package com.vehicle.admin.web.common.shiro.session;

import com.vehicle.common.redis.manager.CacheManager;
import com.vehicle.common.util.SerializeHelper;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by yantingbin on 2017/7/12.
 */
@Component
public class ShiroSessionRepositoryImpl implements ShiroSessionRepository {

    private Logger LOGGER = LoggerFactory.getLogger(ShiroSessionRepositoryImpl.class);

    private static final String REDIS_SHIRO_SESSION_PREFIX = "vehicle-shiro-session:";

    private static final String REDIS_SHIRO_ALL_PREFIX = "*vehicle-shiro-session:*";

    private static final int SESSION_VAL_TIME_SPAN = 18000;

    @Autowired
    private CacheManager cacheManager;

    @Override
    public void saveSession(Session session) {
        if (session == null || session.getId() == null) {
            throw new NullPointerException("session is empty");
        }

        try {
            byte[] key = SerializeHelper.serialize(buildRedisSessionKey(session.getId()));
            if (session.getAttribute(SessionManager.SESSION_STATUS) == null) {
                session.setAttribute(SessionManager.SESSION_STATUS, new SessionStatus());
            }

            byte[] value=SerializeHelper.serialize(session);
            long sessionTimeOut = session.getTimeout() / 1000;
            Long expireTime = sessionTimeOut + SESSION_VAL_TIME_SPAN + (5 * 60);

            cacheManager.set(key, value, expireTime.intValue());

        } catch (InvalidSessionException e) {
            LOGGER.error("shiro save session with an exception");
        }
    }

    @Override
    public void deleteSession(Serializable sessionId) {
        if (sessionId == null) {
            throw new NullPointerException("session id is empty");
        }

        cacheManager.del(buildRedisSessionKey(sessionId));
    }

    @Override
    public Session getSession(Serializable sessionId) {
        if (sessionId == null) {
            throw new NullPointerException("session id is empty");
        }
        try {
            Session session = (Session) SerializeHelper.deserialize(cacheManager.get(SerializeHelper.serialize(buildRedisSessionKey(sessionId))));
            return session;
        } catch (Exception e) {
            LOGGER.error("shiro get session with an exception");
        }
        return null;
    }

    @Override
    public Collection<Session> getAllSessions() {
        Set<Session> sessions = new HashSet<>();

        List<String> keys = cacheManager.getAllKeys(REDIS_SHIRO_ALL_PREFIX);

        keys.forEach(s -> {
            sessions.add(cacheManager.get(s, Session.class));
        });

        return sessions;
    }

    private String buildRedisSessionKey(Serializable sessionId) {
        return REDIS_SHIRO_SESSION_PREFIX + sessionId;
    }
}
